import {Component} from '@angular/core';
import {IonicPage, NavController, NavParams, ToastController} from 'ionic-angular';
import {SideMenuService} from "../../../services/common/side-menu.service";
import {PolicyDetail} from '../../../model/pages/policy/policy-detail/policy-detail';
import {PolicyDetailProvider} from '../../../providers/policy/policy-detail/policy-detail.provider';
import {HttpErrorResponse} from "@angular/common/http";
import {AccountListPage} from "../account-list/account-list";
import {LoadingService} from "../../../services/common/loading.service";
import {ExtraBenefitPage} from "../extra-benefit/extra-benefit";
import * as moment from 'moment';

/**
 * Generated class for the PolicyDetailsPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-policy-details',
  templateUrl: 'policy-details.html',
    providers: [SideMenuService, PolicyDetailProvider, LoadingService]
})
export class PolicyDetailsPage {

    /**
     * 保单id
     * @type {string}
     */
    policyId = '';
    /**
     * 保单详情数据
     * @type {PolicyDetail}
     */
    policyDetail: PolicyDetail = new PolicyDetail();
    /**
     * 下期应缴保费日
     */
    policyPayToDate: number;

    /**
     * 保单状态
     */
    policyStatus: string;
    policyStatusCode: string;

    /**
     * 受益人列表数据
     * @type {any[]}
     */
    BeneficiaryList = [];

    /**
     * 获取受益人数据订阅
     */
    getBeneficiaryListSubscription: any;
    /**
     * 获取保单数据订阅
     */
    getPolicyDetailListSubscription: any;

    /**
     * 是否有附加利益保障
     */
    showExtraBenefit: any;

    /**
     * 用户编码（异地保单）
     */
    agentCode: any;

    /**
     * 异地保单状态
     */
    orphanType: string;

    moment = moment;

    constructor(
        public navCtrl: NavController,
        public navParams: NavParams,
        private sideMenuService: SideMenuService,
        private policyDetailProvider: PolicyDetailProvider,
        private toastController: ToastController,
        private loadingService: LoadingService) {
    }


    ionViewDidLoad() {
        // 获取保单号
        this.policyId = this.navParams.get('policyNO');
        // 下期应缴保费日
        this.policyPayToDate = this.navParams.get('policyPayToDate');
        //保单状态
        this.policyStatus = this.navParams.get('policyStatus');
        this.policyStatusCode = this.navParams.get('policyStatusCode');
        // 迁入迁出标志
        this.orphanType = this.navParams.get('orphanType');
        //agentCode
        this.agentCode = this.navParams.get('agentCode');

        // 查询数据
        if (this.policyId != null && this.policyId != '') {

            // 显示loading动画
            this.loadingService.showLoading();
            // 是否加载完数据
            let isLoad = false;
            // 获取保单信息
            this.getPolicyDetailListSubscription = this.policyDetailProvider.getPolicyList(this.policyId, this.agentCode).subscribe(data => {
                this.policyDetail = data;

                // console.log('identityUL:'+this.policyDetail.identityUL);

                this.showExtraBenefit = this.policyDetail.additionPlanFlag;
                console.log(this.showExtraBenefit);

                // 数据预处理
                for (let key in this.policyDetail) {
                    if (this.policyDetail[key] === '-') {
                        this.policyDetail[key] = '—'
                    }
                    // if (typeof(this.policyDetail[key]) === 'string' && this.policyDetail[key].indexOf(',') >= 0) {
                    //     this.policyDetail[key] = this.policyDetail[key].replace(',', '')
                    // }
                }

                // 获取选择权行使时间
                if (this.policyDetail.timeOption != null) {
                    let list = this.policyDetail.timeOption.split('-');
                    if (list.length > 1) {
                        this.policyDetail.startTimeOption = parseInt(list[0]);
                        this.policyDetail.endTimeOption = parseInt(list[1]);
                    }
                }
                if (isLoad) {
                    // 关闭loading动画
                    this.loadingService.dismissLoading();
                } else {
                    isLoad = true;
                }


                // console.info(data);
            }, (error: HttpErrorResponse) => {
                if (isLoad) {
                    // 关闭loading动画
                    this.loadingService.dismissLoading();
                } else {
                    isLoad = true;
                }
            });

            // 获取受益人信息
            this.getBeneficiaryListSubscription = this.policyDetailProvider.getPolicyBeneficiaryList(this.policyId).subscribe(data => {
                this.BeneficiaryList = data;
                if (isLoad) {
                    // 关闭loading动画
                    this.loadingService.dismissLoading();
                } else {
                    isLoad = true;
                }
            }, (error: HttpErrorResponse) => {

                if (isLoad) {
                    // 关闭loading动画
                    this.loadingService.dismissLoading();
                } else {
                    isLoad = true;
                }
            })
        }

    }

    ionViewWillLeave() {
        // 取消订阅数据
        if (this.getBeneficiaryListSubscription) {
            this.getBeneficiaryListSubscription.unsubscribe();
        }
        // 取消订阅数据
        if (this.getPolicyDetailListSubscription) {
            this.getPolicyDetailListSubscription.unsubscribe();
        }
    }

    /**
     * 返回上一级
     */
    goBack() {
        this.navCtrl.pop();
    }

    openMenu(myEvent) {
        this.sideMenuService.openSideMenu(myEvent)
    }

    /**
     * 跳转至受益人详情
     * @param beneficiary
     * @param {number} index
     */
    goToBeneficiaryDetail(beneficiary: any, index: number) {
        this.navCtrl.push('BeneficiaryDetailPage', {
            beneficiary: beneficiary,
            index: this.BeneficiaryList.length === 1 ? null : index
        });
    }

    /**
     * 跳转至银行转账详情
     * @param {string} id 保单Id
     */
    goToTransferRecordsPage(id: string) {
        this.navCtrl.push('TransferRecordsPage', {
            id: id
        });
    }

    /**
     * 跳转至万能险详情
     * @param {string} id 保单Id
     */
    goToUniversalAccountDetailPage(id: string) {
        this.navCtrl.push('UniversalAccountDetailPage', {
            id: id,
            rulUniversallimitAmount: this.policyDetail.rulUniversallimitAmount,
            displayInd: this.policyDetail.displayInd,
            basePlanCode: this.policyDetail.basePlanCode
        });
    }

    /**
     * 跳转至贷款记录
     * @param {string} id 保单Id
     */
    goToLoanRecordPage(id: string) {
        this.navCtrl.push('LoanRecordPage', {
            id: id,
            currentLoanRate: this.policyDetail.currentLoanRate
        });
    }

    /**
     * 跳转至客户详情
     * @param {string} id 客户id
     */
    goToClientDetail(id: string) {
        this.navCtrl.push('HolderClientDetailPage', {
            clientNum: id
        });
    }

    /**
     * 跳转至投连账户详情
     * @param {string} id 保单id
     */
    goToAccountListPage(id: string) {
        this.navCtrl.push('AccountListPage', {
            id: id
        });
    }

    /**
     * 跳转至附加利益保障
     * @param {string} id
     */
    goToExtraBenefitPage(id: string) {
        this.navCtrl.push('ExtraBenefitPage', {
            id: id
        });
    }

}
